package com.sjzl.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.sjzl.entity.Notification;
import com.sjzl.entity.User;
import com.sjzl.service.UserService;

/**
 * 检查用户是否有新消息
 * @author 黄健
 *
 */
@Aspect
@Component("checkNewMessageInterceptor")
public class CheckNewMessageInterceptor {
	
	@Pointcut("execution(public * com.sjzl.action.BoardAction.list(..))")
	public void bList(){};
	
	@Pointcut("execution(public * com.sjzl.action.UserAction.selectMessage(..))")
	public void afterSelectMessage(){};
	
	@Resource(name="userServiceImpl")
	private UserService userService;
	
	@Before("bList()")
	public void check(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession httpSession = request.getSession();
		ActionContext actionContext=ActionContext.getContext();
		
		User sessionUser = (User) httpSession.getAttribute("sessionUser");
		if(sessionUser!=null){
			User dbUser = userService.get(User.class, sessionUser.getId());
			List<Notification> notifications = dbUser.getNotifications();
			if(notifications.size()==0){
				actionContext.getSession().put("newMessage", false);
				return;
			}
			for(Notification n : notifications){
				if(n.getIsNew()==1){
					actionContext.getSession().put("newMessage", true);
				}else{
					actionContext.getSession().put("newMessage", false);
				}
			}
		}
	}
	
	@After("afterSelectMessage()")
	public void checkSelectMessage(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession httpSession = request.getSession();
		ActionContext actionContext=ActionContext.getContext();
		
		User sessionUser = (User) httpSession.getAttribute("sessionUser");
		if(sessionUser!=null){
			User dbUser = userService.get(User.class, sessionUser.getId());
			List<Notification> notifications = dbUser.getNotifications();
			if(notifications.size()==0){
				actionContext.getSession().put("newMessage", false);
				return;
			}
			for(Notification n : notifications){
				if(n.getIsNew()==1){
					actionContext.getSession().put("newMessage", true);
				}else{
					actionContext.getSession().put("newMessage", false);
				}
			}
		}
	}
	
}
